package com.ld.admin.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;

import com.alibaba.fastjson.JSON;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.web.util.Web;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ShiroUtils {

    /** 私有构造器 **/
    private ShiroUtils() {
    }

    /**
     * 获取当前用户Session
     * 
     * @Return SysUserEntity 用户信息
     */
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * 用户登出
     */
    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    /**
     * 获取当前用户信息
     * 
     * @Return SysUserEntity 用户信息
     */
    public static User getUserInfo() {
        return (User) SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * 是否是ajax请求
     * 
     * @Title isAjax
     * @author 吕凯
     * @date 2020年10月19日 下午4:40:51
     * @param request
     * @return boolean
     */
    public static boolean isAjax(ServletRequest request) {
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public static void sendJsonErrMsg(ServletResponse response, String message) {
        response.setContentType("text/json;charset=UTF-8");
        Result result = Web.Response.error(message);
        try {
            response.getWriter().print(JSON.toJSON(result));
        } catch (IOException e) {
            log.error("", e);
        }
    }

    public static void sendJsonSuccMsg(ServletResponse response, String message) {
        response.setContentType("text/json;charset=UTF-8");
        Result result = Web.Response.success(message);
        try {
            response.getWriter().print(JSON.toJSON(result));
        } catch (IOException e) {
            log.error("", e);
        }
    }

}